import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_flexible/utils/gps/gps_util.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../models/login.m.dart';
import '../../../routes/route_name.dart';
import '../../../utils/gps/gps_util.dart';
import '../../../utils/tool/log_util.dart';
import '../../../services/gps_service.dart';
import '../../../utils/tool/user_util.dart';

// to ensure this is executed
// run app from xcode, then from xcode menu, select Simulate Background Fetch

@pragma('vm:entry-point')
Future<bool> onIosBackground(ServiceInstance service) async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();

  SharedPreferences preferences = await SharedPreferences.getInstance();
  await preferences.reload();
  final log = preferences.getStringList('log') ?? <String>[];
  log.add(DateTime.now().toIso8601String());
  await preferences.setStringList('log', log);

  print("苹果后台执行");


  return true;
}

Timer? _timer;

@pragma('vm:entry-point')
void onStart(ServiceInstance service) async {
  // Only available for flutter 3.0.0 and later
  DartPluginRegistrant.ensureInitialized();

  // For flutter prior to version 3.0.0
  // We have to register the plugin manually

  SharedPreferences preferences = await SharedPreferences.getInstance();
  await preferences.setString("hello", "world");

  /// OPTIONAL when use custom notification
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

  if (service is AndroidServiceInstance) {
    service.on('setAsForeground').listen((event) {
      service.setAsForegroundService();
    });

    service.on('setAsBackground').listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on('stopService').listen((event) {
    _timer?.cancel();
    _timer = null;
    service.stopSelf();
  });

  // Position lp = Position(longitude: 0
  //     , latitude: 0
  //     , timestamp: new DateTime(2025)
  //     , accuracy: 0
  //     , altitude: 0
  //     , altitudeAccuracy: 0
  //     , heading: 0
  //     , headingAccuracy: 0
  //     , speed: 0
  //     , speedAccuracy: 0);

  // bring to foreground
  _timer = Timer.periodic(const Duration(seconds: 5), (timer) async {



    print("work manager task start");
    // Future<Position> fp = GpsUtil.determinePosition();
    // fp.then((p) {
    //   LogUtil.d('work manager task 获取到的GPS：${p.longitude} : ${p.latitude}');
    //   postLocation({"longitude":p.longitude,"latitude":p.latitude});
    //
    // }).catchError((msg){
    //   LogUtil.d("work manager 读取失败");
    // });


    if (service is AndroidServiceInstance) {
      if (await service.isForegroundService()) {
        /// OPTIONAL for use custom notification
        /// the notification id must be equals with AndroidConfiguration when you call configure() method.
        // flutterLocalNotificationsPlugin.show(
        //   888,
        //   'COOL SERVICE',
        //   'Awesome 位置',
        //   const NotificationDetails(
        //     android: AndroidNotificationDetails(
        //       '位置获取',
        //       '前台',
        //       icon: 'ic_bg_service_small',
        //       ongoing: true,
        //     ),
        //   ),
        // );

        // if you don't using custom notification, uncomment this
        // service.setForegroundNotificationInfo(
        //   title: "位置获取",
        //   content: "Updated at ${DateTime.now()}",
        // );
      }
    }
    var tt = await UserUtil.getToken();
    print("缓存中获取的token$tt");
    /// you can see this log in logcat
    debugPrint('FLUTTER BACKGROUND SERVICE: ${DateTime.now()}');

    GpsUtil.determinePosition().then((p){
      debugPrint("坐标${p.longitude} ,${p.latitude},$tt");
        postLocation({"longitude":p.longitude,"latitude":p.latitude,"token":tt});
    });


    // test using external plugin
    final deviceInfo = DeviceInfoPlugin();
    String? device;
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfo.androidInfo;
      device = androidInfo.model;
    } else if (Platform.isIOS) {
      final iosInfo = await deviceInfo.iosInfo;
      device = iosInfo.model;
    }

    service.invoke(
      'update',
      {
        "current_date": DateTime.now().toIso8601String(),
        "device": device,
      },
    );
  });
}


class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _BaiduMapDemoState();
}

class _BaiduMapDemoState extends State<Home> {
  late final WebViewController controller;
  bool _canGoBack = false;
  bool _isLoading = true;
  String td = '';
  double height = 0;
  @override
  void initState() {

    super.initState();
    UserUtil.getToken().then((result){
      setState(() {
        _isLoading = false;
        controller = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onProgress: (int progress) {
                // Update loading bar.
              },
              onPageStarted: (String url) {},
              onPageFinished: (String url) {},
              onHttpError: (HttpResponseError error) {},
              onWebResourceError: (WebResourceError error) {},
              onNavigationRequest: (NavigationRequest request) {
                if (request.url.startsWith('https://www.youtube.com/')) {
                  return NavigationDecision.prevent;
                }
                return NavigationDecision.navigate;
              },
            ),
          )
        // 注册JavaScript频道
          ..addJavaScriptChannel(
            'FlutterWebViewChannel',
            onMessageReceived: (JavaScriptMessage message) {
              // 处理来自JS的消息
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('收到JS消息: ${message.message}')),
              );
              // 根据消息内容执行不同操作
              if (message.message == 'refresh') {
                controller.reload();
              } else if (message.message.startsWith('logout:')) {
                // 处理数据
                UserUtil.cleanToKen().then((a){
                  final service = FlutterBackgroundService();
                  service.invoke("stopService");
                  Navigator.pushReplacementNamed(context, RouteName.login);
                });

              } else if (message.message.startsWith('data:')) {
                // 处理数据
                final data = message.message.split(':')[1];
                print('收到数据: $data');
              }
            },
          )
          ..loadRequest(Uri.parse('http://192.168.0.100:8081/#/?token=$result'));
      });

    });


    init();
    FlutterBackgroundService().invoke("setAsBackground");
  }
  // 更新是否可以返回的状态
  Future<void> _updateCanGoBack() async {
    final canGoBack = await controller.canGoBack();
    if (mounted && canGoBack != _canGoBack) {
      setState(() {
        _canGoBack = canGoBack;
      });
    }
  }


  Future<void> token() async {
    final result = await UserUtil.getToken();
    setState(() {
      td = result;
    });
  }

  // 处理返回逻辑
  Future<bool> _handleBack(BuildContext context) async {
    if (_canGoBack) {
      // WebView 可以回退，优先回退 WebView 历史
      await controller.goBack();
      _updateCanGoBack();
      return false; // 拦截原生返回
    } else {
      // WebView 无法回退，允许原生返回
      return true;
    }
  }
  // PopScope 的拦截回调
  Future<bool> _onPopInvoked(bool didPop) async {
    if (didPop) return true; // 如果已经执行了 pop，直接返回

    if (_canGoBack) {
      await controller.goBack();
      _updateCanGoBack();
      return false; // 拦截 pop
    } else {
      return true; // 允许 pop
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    }

    if (controller == null) {
      return Center(child: Text('加载WebView失败'));
    }

    return PopScope(
      canPop: _canGoBack, // 控制返回按钮是否启用
      onPopInvoked: _onPopInvoked,
      child: Scaffold(body: WebViewWidget(controller: controller),
      ),
    );
  }




  Future<void> init() async {
    WidgetsFlutterBinding.ensureInitialized();
    await initializeService();
  }

  Future<void> initializeService() async {

    final service = FlutterBackgroundService();

    /// OPTIONAL, using custom notification channel id
    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'my_foreground', // id
      'MY FOREGROUND SERVICE', // title
      description:
      'This channel is used for important notifications.', // description
      importance: Importance.low, // importance must be at low or higher level
    );

    final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

    if (Platform.isIOS || Platform.isAndroid) {
      await flutterLocalNotificationsPlugin.initialize(
        const InitializationSettings(
          iOS: DarwinInitializationSettings(),
          android: AndroidInitializationSettings('ic_bg_service_small'),
        ),
      );
    }

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);

    await service.configure(
      androidConfiguration: AndroidConfiguration(
        // this will be executed when app is in foreground or background in separated isolate
        onStart: onStart,
        // auto start service
        autoStart: true,
        autoStartOnBoot:true,
        isForegroundMode: true,
        notificationChannelId: 'my_foreground',
        initialNotificationTitle: '位置服务',
        initialNotificationContent: '请勿关闭',
        foregroundServiceNotificationId: 888,
        foregroundServiceTypes: [AndroidForegroundType.location],
      ),
      iosConfiguration: IosConfiguration(
        // auto start service
        autoStart: true,
        // this will be executed when app is in foreground in separated isolate
        onForeground: onStart,
        // you have to enable background fetch capability on xcode project
        onBackground: onIosBackground,
      ),
    );
  }

}
